// 倒计时函数
import { ref, computed, onUnmounted } from 'vue'
import { dayjs } from 'element-plus'
export default function useCountdown() {
  // 定义定时器
  let timer = null
  // 展示的时间
  const time = ref(0)
  const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
  // 倒计时函数逻辑
  const start = (seconds, router) => {
    time.value = seconds
    timer = setInterval(() => {
      time.value--
      // 如果订单超时，取消定时器，取消订单，跳转回首页
      if (time.value <= 0) {
        timer && clearInterval(timer)
        router.push('/')
      }
    }, 1000)
  }
  // 组件销毁时清除定时器
  onUnmounted(() => {
    timer && clearInterval(timer)
  })
  return {
    formatTime,
    start,
  }
}
